package com.alarm.ecp.utils;

import com.alarm.ecp.pojo.Coordinate;
import com.alarm.ecp.pojo.RouteStep;

import java.util.ArrayList;
import java.util.List;

public class RouteDeviationDetector {
    private List<RouteStep> steps;
    private int currentStepIndex;
    private static final double DEVIATION_THRESHOLD = 20.0; // 偏离阈值，单位：米

    public RouteDeviationDetector(List<RouteStep> steps) {
        this.steps = steps;
        this.currentStepIndex = 0;
    }

    // 处理当前位置更新
    public void updateCurrentPosition(double longitude, double latitude) {
        System.out.println("当前位置：" + longitude + ", " + latitude);
        if (currentStepIndex >= steps.size()) {
            System.out.println("已到达目的地");
            return;
        }

        RouteStep currentStep = steps.get(currentStepIndex);

        // 检查是否偏离当前步骤的路径
        if (isDeviatedFromStep(currentStep, longitude, latitude)) {
            System.out.println("警告：您已偏离航线！请返回正确路线。");
            return;
        }

        // 检查是否已完成当前步骤
        if (isStepCompleted(currentStep, longitude, latitude)) {
            currentStepIndex++;
            if (currentStepIndex < steps.size()) {
                RouteStep nextStep = steps.get(currentStepIndex);
                System.out.println("步骤完成，进入下一步：" + nextStep.getInstruction());
                return;
            } else {
                System.out.println("恭喜您已到达目的地！");
                return;
            }
        }

        double f = calculateDistance(new Coordinate(longitude, latitude), currentStep.getPolyline().get(currentStep.getPolyline().size() - 1)) ;
        System.out.println(String.format("请继续行驶向前行驶%s米", (int)f));


    }

    // 检查是否偏离当前步骤
    private boolean isDeviatedFromStep(RouteStep step, double longitude, double latitude) {
        Coordinate currentPos = new Coordinate(longitude, latitude);
        double minDistance = Double.MAX_VALUE;

        for (Coordinate point : step.getPolyline()) {
            double distance = calculateDistance(currentPos, point);
            if (distance < minDistance) {
                minDistance = distance;
            }
        }

        return minDistance > DEVIATION_THRESHOLD;
    }

    // 检查是否已完成当前步骤
    private boolean isStepCompleted(RouteStep step, double longitude, double latitude) {
        Coordinate lastPoint = step.getPolyline().get(step.getPolyline().size() - 1);
        Coordinate currentPos = new Coordinate(longitude, latitude);

        double distanceToEnd = calculateDistance(currentPos, lastPoint);

        // 如果距离终点很近，则认为已完成当前步骤
        return distanceToEnd < DEVIATION_THRESHOLD;
    }

    // 计算两个坐标点之间的距离（简化版Haversine公式）
    public double calculateDistance(Coordinate a, Coordinate b) {
        double earthRadius = 6371000; // 地球半径，单位：米
        double dLat = Math.toRadians(b.latitude - a.latitude);
        double dLon = Math.toRadians(b.longitude - a.longitude);

        double lat1 = Math.toRadians(a.latitude);
        double lat2 = Math.toRadians(b.latitude);

        double x = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
        double y = 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1-x));

        return earthRadius * y;
    }

    public static void main(String[] args) {
        // 示例使用
        List<RouteStep> steps = parseRouteStepsFromJson();
        RouteDeviationDetector detector = new RouteDeviationDetector(steps);

        detector.updateCurrentPosition(116.434323, 39.909041);

        // 模拟位置更新
        // 第一步路径上的点
        detector.updateCurrentPosition(116.434323, 39.909041);
        detector.updateCurrentPosition(116.434500, 39.909041);

        // 接近第一步终点
        detector.updateCurrentPosition(116.434965, 39.909041);

        // 第二步路径上的点
        detector.updateCurrentPosition(116.434965, 39.909028);
        detector.updateCurrentPosition(116.434931, 39.908932);

        // 偏离路径的测试点
        detector.updateCurrentPosition(116.435500, 39.908500); // 应该触发偏离警告

        // 继续正常路径
        detector.updateCurrentPosition(116.434887, 39.908867);
        detector.updateCurrentPosition(116.435009, 39.908077); // 第二步终点

        // 第三步路径
        detector.updateCurrentPosition(116.434891, 39.908073);
        detector.updateCurrentPosition(116.434449, 39.908073); // 到达目的地
    }

    // 从JSON解析路径步骤（示例）
    private static List<RouteStep> parseRouteStepsFromJson() {
        List<RouteStep> steps = new ArrayList<>();

        // 第一步
        List<Coordinate> step1Polyline = new ArrayList<>();
        step1Polyline.add(new Coordinate(116.434323, 39.909041));
        step1Polyline.add(new Coordinate(116.434965, 39.909041));
        steps.add(new RouteStep("骑行54米右转", step1Polyline));

        // 第二步
        List<Coordinate> step2Polyline = new ArrayList<>();
        step2Polyline.add(new Coordinate(116.434965, 39.909041));
        step2Polyline.add(new Coordinate(116.434965, 39.909028));
        step2Polyline.add(new Coordinate(116.434931, 39.908932));
        step2Polyline.add(new Coordinate(116.434887, 39.908867));
        step2Polyline.add(new Coordinate(116.434887, 39.908867));
        step2Polyline.add(new Coordinate(116.434831, 39.908724));
        step2Polyline.add(new Coordinate(116.434818, 39.908655));
        step2Polyline.add(new Coordinate(116.434818, 39.908542));
        step2Polyline.add(new Coordinate(116.434826, 39.908424));
        step2Polyline.add(new Coordinate(116.434883, 39.908303));
        step2Polyline.add(new Coordinate(116.434883, 39.908303));
        step2Polyline.add(new Coordinate(116.434974, 39.908194));
        step2Polyline.add(new Coordinate(116.434996, 39.908142));
        step2Polyline.add(new Coordinate(116.435009, 39.908103));
        step2Polyline.add(new Coordinate(116.435009, 39.908077));
        steps.add(new RouteStep("沿建国门北大街向南骑行114米右转", step2Polyline));

        // 第三步
        List<Coordinate> step3Polyline = new ArrayList<>();
        step3Polyline.add(new Coordinate(116.435009, 39.908073));
        step3Polyline.add(new Coordinate(116.434891, 39.908073));
        step3Polyline.add(new Coordinate(116.434891, 39.908073));
        step3Polyline.add(new Coordinate(116.434449, 39.908073));
        steps.add(new RouteStep("骑行47米到达目的地", step3Polyline));

        return steps;
    }
}
